<!--
* @author: lzm
* @date: 2023年11月27日10:52:10
* @description：物料管理页面
* @update: 2023年11月27日10:52:16
-->
<template>
  <div class="container">
    <div class="app-container">
      <div class="material-top form-top">
        <el-form ref="materialForm" :model="materialForm" label-width="90px">
          <el-row>
            <el-col :span="9">
              <el-form-item label="物料名称">
                <el-select
                  v-model="materialForm.name"
                  filterable
                  placeholder="请选择物料名称"
                >
                  <el-option
                    v-for="(item, index) in materialName"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col style="padding-left: 12px" :span="9">
              <el-form-item label="规格型号">
                <el-select
                  v-model="materialForm.model"
                  filterable
                  placeholder="请选择规格型号"
                >
                  <el-option
                    v-for="(item, index) in standardsList"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right; padding-right: 10px;">
              <el-button type="primary" class="chamfer-98" @click="searchBtn"
                >查询</el-button
              >
              <el-button
                style="margin-left: 10px"
                class="chamfer-98"
                plain
                @click="resetBtn"
                >重置</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="material-bot table-normal">
        <div class="btnBox">
          <div class="left_btn">
            <el-button type="primary" class="chamfer-98" @click="addBtn">
              <span class="btn-middle">
                <span>新增</span>
                <img class="btn-icon" src="~@/assets/material_img/addBtn.png" />
              </span>
            </el-button>
            <el-button
              type="primary"
              class="chamfer-98 greenBtn"
              @click="importBtn"
            >
              <span class="btn-middle">
                <span>导入</span>
                <img
                  class="btn-icon"
                  src="~@/assets/material_img/importBtn.png"
                />
              </span>
            </el-button>
            <el-button type="primary" class="chamfer-98" @click="downloadBtn">
              <span class="btn-middle">
                <span>下载模版</span>
                <img
                  class="btn-icon"
                  src="~@/assets/material_img/downloadBtn.png"
                />
              </span>
            </el-button>
          </div>
          <div class="right_btn">
            <el-button type="warning" class="chamfer-98" @click="delBtn">
              <span class="btn-middle">
                <span>删除</span>
                <img class="btn-icon" src="~@/assets/material_img/delBtn.png" />
              </span>
            </el-button>
            <el-button type="primary" class="chamfer-98" @click="exportBtn">
              <span class="btn-middle">
                <span>导出</span>
                <img
                  class="btn-icon"
                  src="~@/assets/material_img/exportBtn.png"
                />
              </span>
            </el-button>
          </div>
        </div>
        <el-table
          v-loading="loading"
          element-loading-background="rgba(0, 0, 0, 0.6)"
          :data="materialTable"
          :row-key="getRowKeys"
          fit
          style="width: 100%"
          header-row-class-name="tableHeader"
          header-cell-class-name="tableTrHeader"
          row-class-name="tableRow"
          cell-class-name="tableCell"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="80"
            :reserve-selection="true"
            label-class-name="DisabledSelection"
          />
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column
            prop="name"
            label="物料名称"
            width="140"
            align="center"
          >
            <template v-slot="{row}">
              <div style="white-space: pre;" v-html="row.name"></div>
            </template>
          </el-table-column>
          <el-table-column
            prop="model"
            label="规格型号"
            width="140"
            align="center"
          />
          <el-table-column
            prop="totalCount"
            label="实际数量"
            width="100"
            align="center"
          />
          <el-table-column
            prop="warnCount"
            label="预警数量"
            width="140"
            align="center"
          >
            <template v-slot="{ row }">
              <div v-if="row.isWarnEdit">
                <el-input
                  class="editInput"
                  v-model="row.backups.warnCount"
                  :ref="'warn' + row.id"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  maxLength='9'
                ></el-input>
                <i
                  class="el-icon-check rightIcon"
                  @click.stop="confirmWarn(row)"
                ></i>
              </div>
              <div v-else>
                <span class="weight">
                  {{ row.warnCount }}
                </span>
                <div class="editBtn" @click="editWarning(row)"></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="singleWeight"
            label="单重/g"
            width="140"
            align="center"
          >
            <template v-slot="{ row }">
              <div v-if="row.isWeightEdit">
                <el-input
                  class="editInput"
                  v-model="row.backups.singleWeight"
                  :ref="'weight' + row.id"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  maxLength='9'
                ></el-input>
                <i
                  class="el-icon-check rightIcon"
                  @click.stop="confirmWeight(row)"
                ></i>
              </div>
              <div v-else>
                <span class="weight">
                  {{ row.singleWeight }}
                </span>
                <div class="editBtn" @click="editWeight(row)"></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="{ row }">
              <div class="editBox" @click="editBtn(row)">
                编辑
                <div class="editBtn"></div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <paging-component
          :total="total"
          :page-size="materialForm.currentSize"
          :current-page="materialForm.currentPage"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </div>
      <!-- 物料新增编辑弹窗 -->
      <material-dialog
        :id.sync="id"
        ref="editMaterial"
        :show-dialog.sync="showDialog"
        :title="title"
        @updateList="renderList"
      />
      <!-- excel导入弹窗 -->
      <import-excel
        modelName="物料"
        :show-excel-dialog.sync="showExcelDialog"
        @importFn="importFn"
      />
      <!-- 删除弹窗 -->
      <del-dialog
        ref="delMaterial"
        :showDelDialog.sync="showDelDialog"
        @delFn="delFn"
      />
    </div>
  </div>
</template>
<script>
import {
  getMaterialList,
  delMaterialList,
  getMaterialNameList,
  getMaterialModelList,
  updateWarnCount,
  updateSingleWeight,
  downloadExportTemplate,
  importExportList,
  exportExportList
} from '@/api/materialManage'
import materialDialog from './components/materialDialog.vue'
import importExcel from '@/components/ImportExcel/index.vue'
import pagingComponent from '@/components/PagingComponent/index.vue'
import delDialog from '@/components/delDialog/index.vue'
export default {
  components: { materialDialog, importExcel, pagingComponent, delDialog },
  data() {
    return {
      // 物料表单
      materialForm: {
        name: '', // 物料名称
        model: '', // 规格型号
        currentPage: 1, // 页码
        currentSize: 20 // 页尺寸
      },
      total: 0, // 总条数
      weightTurn: true, // 控制重量编辑
      // 物料名称
      materialName: [],
      // 规格型号
      standardsList: [],
      // 物料列表
      materialTable: [],
      showExcelDialog: false, // 控制excel导入弹层
      showDialog: false, // 控制弹层
      showDelDialog: false, // 控制删除弹层
      title: '新增物料', // 弹层标题
      id: '', // 物料id
      multipleSelection: [], // 表格选中数据
      loading: true // 表格加载
    }
  },
  async created() {
    this.renderList()
  },
  methods: {
    // 获取列表
    async renderList() {
      this.loading = true
      const { result } = await getMaterialList(this.materialForm)
      this.total = Number(result.totalCount)
      this.materialTable = result.currentData
      this.materialTable.forEach((item) => {
        this.$set(item, 'isWarnEdit', false)
        this.$set(item, 'isWeightEdit', false)
        this.$set(item, 'backups', {
          id: item.id,
          warnCount: item.warnCount,
          singleWeight: item.singleWeight
        })
      })
      // 更新下拉菜单数据
      let { result: list1 } = await getMaterialNameList()
      this.materialName = list1
      let { result: list2 } = await getMaterialModelList()
      this.standardsList = list2
      this.loading = false
    },
    // 查询
    searchBtn() {
      this.materialForm.currentPage = 1
      this.renderList()
    },
    // 重置
    resetBtn() {
      this.materialForm = {
        name: '', // 物料名称
        model: '', // 规格型号
        currentPage: 1, // 页码
        currentSize: 20 // 页尺寸
      }
      this.renderList()
    },
    // pageSize改变时会触发(每页数据条数)
    handleSizeChange(val) {
      this.materialForm.currentSize = val
      this.renderList()
    },
    // currentPage改变时会触发(当前页码数)
    handleCurrentChange(val) {
      this.materialForm.currentPage = val
      this.renderList()
    },
    // 添加
    addBtn() {
      this.showDialog = true
      this.title = '新增物料'
    },
    // 编辑
    editBtn(row) {
      this.id = row.id
      this.title = '编辑物料'
      this.showDialog = true
    },
    // 导入
    importBtn() {
      this.showExcelDialog = true
    },
    async importFn(data) {
      const loading = this.$loading({
          lock: true,
          text: '正在导入中，请耐心等待...',
          background: 'rgba(0, 0, 0, 0.6)'
      });
      await importExportList(data)
        .then((result) => {
          this.showExcelDialog = false
          this.$message({
            type: 'success',
            message: '导入成功'
          })
          this.renderList()
        })
        .catch((err) => {
          this.$message({
            type: 'error',
            message: '导入失败'
          })
        })
        .finally(() => {
          loading.close()
        })
    },
    // 下载
    async downloadBtn() {
      await downloadExportTemplate()
        .then((result) => {
          const content = result
          const blob = new Blob([content], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          }) //处理返回
          const fileName = '物料信息模板.xlsx'
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
        .catch((err) => {
          this.$message({
            type: 'error',
            message: '下载失败!'
          })
        })
    },
    // 删除
    delBtn() {
      // 校验：数据应大于一条
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择要删除的数据!'
        })
        return
      }
      this.showDelDialog = true
    },
    async delFn() {
      // 创建一个数组，里面存勾选数据的id
      let delArrayData = []
      this.multipleSelection.forEach((item) => {
        delArrayData.push(item.id)
      })
      await delMaterialList(delArrayData)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.showDelDialog = false
      if(this.materialTable.length === this.multipleSelection.length){
        if(this.materialForm.currentPage > 1){
          this.materialForm.currentPage--
        }
      }
      this.renderList()
    },
    // 导出
    async exportBtn() {
      if (this.multipleSelection.length > 0) {
        // 创建一个数组，里面存勾选数据的id
        let delArrayData = []
        this.multipleSelection.forEach((item) => {
          delArrayData.push(item.id)
        })
        await exportExportList({ ids: delArrayData })
          .then((result) => {
            const content = result
            const blob = new Blob([content], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }) //处理返回
            const fileName = '物料信息.xlsx'
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          })
          .catch((err) => {
            this.$message({
              type: 'error',
              message: '导出失败!'
            })
          })
      } else {
        await exportExportList(this.materialForm)
          .then((result) => {
            const content = result
            const blob = new Blob([content], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }) //处理返回
            const fileName = '物料信息.xlsx'
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          })
          .catch((err) => {
            this.$message({
              type: 'error',
              message: '导出失败!'
            })
          })
      }
    },
    // 设置预警数量
    editWarning(row) {
      row.isWarnEdit = true
      // 获取焦点
      this.$nextTick(() => {
        let id = 'warn' + row.id
        this.$refs[id].focus()
      })
    },
    // 修改预警数量
    async confirmWarn(row) {
      row.isWarnEdit = false
      await updateWarnCount({
        id: row.id,
        number: row.backups.warnCount
      })
      this.$message.success('修改预警数量成功！')
      this.renderList()
    },
    // 设置单重数量
    editWeight(row) {
      row.isWeightEdit = true
      this.$nextTick(() => {
        let id = 'weight' + row.id
        this.$refs[id].focus()
      })
    },
    async confirmWeight(row) {
      row.isWeightEdit = false
      await updateSingleWeight({
        id: row.id,
        weight: row.backups.singleWeight
      })
      this.$message.success('修改单重数量成功！')
      this.renderList()
    },
    // 获取勾选数据表格
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每行的唯一key值 用其id表示
    getRowKeys(row) {
      return row.id
    },
    // 失去焦点时触发(预警数量)
    // blurWarn(row) {
    //   row.isWarnEdit = false
    //   row.backups.warnCount = row.warnCount
    // },
    // 失去焦点时触发(单重数量)
    // blurWeight(row) {
    //   row.isWeightEdit = false
    //   row.backups.singleWeight = row.singleWeight
    // },
  }
}
</script>
<style lang="scss">
@import '~@/styles/_handle.scss';
.greenBtn {
  @include background('import_btn_color');
  @include border_color('import_btn_color');
  &:hover {
    @include background('import_btn_color');
  }
}
.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  @include background('table_hover_color');
}
</style>
<style scoped lang="scss">
@import '~@/styles/_handle.scss';
.container {
  height: 100%;
  padding: 24px 30px;
  .app-container {
    width: 100%;
    height: 100%;
    padding: 25px;
    border: 1px solid;
    @include border_image('container_border');
    @include background('content_bg_color');
  }
}

::v-deep .app-container {
  .material-top {
    height: 44px;
    .el-form-item {
      margin-bottom: 0px;
    }
    .chamfer-98,
    .chamfer-corners-8 {
      font-size: 18px;
    }
  }
  .material-bot {
    height: 100%;
    padding: 15px 10px;
    .btnBox {
      height: 44px;
      .left_btn,
      .right_btn {
        .chamfer-98 {
          font-size: 18px;
          text-align: center;
          .btn-middle {
            display: flex;
            align-items: center;
            .btn-icon {
              margin-left: 4px;
              width: 16px;
              height: 16px;
            }
          }
          &:nth-child(3n) {
            width: 135px;
          }
        }
      }
      .left_btn {
        float: left;
      }
      .right_btn {
        float: right;
      }
    }
    .el-table {
      height: calc(100% - 120px);
      .el-table__body-wrapper{
        height: calc(100% - 48px);
        overflow-y: auto;
      }
      .el-table__body-wrapper::-webkit-scrollbar{
        width: 6px;
        height: 8px;
      }
      .tableTrHeader {
        border: none;
      }
      .el-input__inner {
        height: 30px;
      }
    }
  }
}
.editBox {
  font-size: 18px;
  @include font_color('material_edit_color');
  cursor: pointer;
}
.editBtn {
  display: inline-block;
  margin-left: 3px;
  width: 16px;
  height: 16px;
  @include background('material_edit_icon');
}
// 暂无数据时展示样式
::v-deep .el-table__empty-block {
  min-height: 240px;
  font-size: 20px;
}
// 取消表格底部横线
// ::v-deep .el-table--border::after,
// .el-table--group::after,
// .el-table::before {
//   content: none;
// }
// 修改小图标样式
.rightIcon {
  margin-left: 5px;
  font-size: 20px;
  font-weight: 700;
  @include font_color('material_edit_color');
}
// 正常展示宽度
.weight {
  width: 70px;
  display: inline-block;
}
.editInput {
  width: 70px;
  height: 30px;
  .el-input__inner {
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
  }
}

::v-deep .el-input-number .el-input-number__increase {
  display: none;
}

::v-deep .el-input-number .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number.is-controls-right .el-input__inner {
  padding-right: 0;
  padding-left: 0;
}
</style>
